/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 模板消息链接替换
 */
import React, { useState, useCallback, useEffect, useMemo } from "react";
import { connect } from "dva";
import { Form, Input, Row, Col, Button, Radio, message } from "antd";
import { isEmpty } from "lodash";
import styles from "../style.less";

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 5 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 15 },
  },
};

const changeTime = (data = 0) => {
  if (isNaN(data)) return;
  const hours = ((Number(data) / 60 / 60) % 24).toString().split(".")[0];
  const day = (Number(data) / 60 / 60 / 24).toString().split(".")[0];
  return { day, hours };
};

const ChangeTemplateLink = props => {
  const { dispatch, form, templateData = {}, platformList } = props;
  const { getFieldDecorator, validateFields } = form;
  const { url, miniprogram = {}, expireIn } = templateData;
  const [showEdit, setShowEdit] = useState(true);
  const [channel, setChannel] = useState("web");
  const [restTime, setRestTime] = useState(1 * 24 * 60 * 10);

  const { day, hours } = useMemo(() => changeTime(restTime), [restTime]);

  useEffect(
    () => {
      setRestTime(expireIn);
    },
    [expireIn]
  );

  useEffect(
    () => {
      const { weixin: { platform } = {} } = platformList;
      if (!platform) {
        message.warn("暂无绑定的微信公众号平台，请先到”微信管理-设置”中新增关联！");
        return;
      }
      dispatch({
        type: "massPush/checkTemplate",
        payload: {
          platform,
        },
      }).then(res => {
        const { data } = res;
        if (!isEmpty(data)) {
          setShowEdit(false);
          if (data.miniprogram) {
            setChannel("wx_app");
          }
        } else {
          setShowEdit(true);
        }
      });
    },
    [dispatch, platformList]
  );

  const handleOk = useCallback(() => {
    validateFields((err, val) => {
      if (err) return;
      const { channel, link, webLink, wx_app, wx_app_back_link, expire_in } = val;
      const { weixin: { platform } = {} } = platformList;
      setRestTime(expire_in * 24 * 60 * 60);
      const payload = {
        platform,
        expire_in,
      };
      if (!platform) {
        message.warn("暂无绑定的微信公众号平台，请先到”微信管理-设置”中新增关联！");
        return;
      }
      if (channel === "web") {
        payload.url_info = {
          url: webLink,
        };
      } else {
        payload.url_info = {
          url: wx_app_back_link,
          miniprogram: {
            appid: wx_app,
            pagepath: link,
          },
        };
      }
      dispatch({
        type: "massPush/saveTemplate",
        payload,
      }).then(() => {
        setShowEdit(false);
      });
    });
  }, []);

  const handleCancel = useCallback(
    () => {
      setChannel(channel);
      setShowEdit(true);
    },
    [channel]
  );

  const onRadioChange = useCallback(e => {
    const { value } = e.target;
    value == "web" ? setChannel("web") : setChannel("wx_app");
  }, []);

  const formItems = useMemo(
    () =>
      channel == "web"
        ? [
            {
              field: "webLink",
              label: "跳转链接",
              rules: [
                {
                  required: true,
                  message: "请输入链接",
                },
              ],
              input: {
                initialValue: url,
                placeholder: "请输入或黏贴链接（例如：http://www.***.com)",
                title: url,
                disabled: !showEdit,
              },
            },
          ]
        : [
            {
              field: "link",
              label: "小程序跳转链接",
              rules: [
                {
                  required: true,
                  message: "请输入链接",
                },
              ],
              input: {
                initialValue: miniprogram.pagepath,
                placeholder: "请输入或黏贴链接（例如：/page/index）",
                title: miniprogram.pagepath,
                disabled: !showEdit,
              },
            },
            {
              field: "wx_app",
              label: "小程序ID",
              rules: [
                {
                  required: true,
                  message: "请输入小程序APPID",
                },
              ],
              input: {
                initialValue: miniprogram.appid,
                placeholder: "请输入小程序APPID（例如：wx*********）",
                title: miniprogram.appid,
                disabled: !showEdit,
              },
            },
            {
              field: "wx_app_back_link",
              label: "H5备用链接",
              rules: [],
              input: {
                initialValue: url,
                placeholder: "请输入H5备用链接（例如：http://www.***.com）",
                title: url,
                disabled: !showEdit,
              },
            },
          ],
    [channel, miniprogram, showEdit, url]
  );

  return (
    <div>
      <Row type="flex" justify="space-between">
        <Col span={10}>
          <Row gutter={[0, 18]}>
            <Col>
              <Row type="flex" justify="space-between" style={{ fontSize: 16 }}>
                <Col>“取出快件通知”模板跳转链接替换为：</Col>
              </Row>
            </Col>
            <Col>
              <Form layout="horizontal" {...formItemLayout}>
                {showEdit && (
                  <FormItem label="选择渠道">
                    {getFieldDecorator("channel", {
                      initialValue: channel,
                    })(
                      <RadioGroup onChange={onRadioChange}>
                        <Radio value="web">跳转网页</Radio>
                        <Radio value="wx_app">小程序</Radio>
                      </RadioGroup>
                    )}
                  </FormItem>
                )}
                {formItems.map(val => {
                  const { field, label, rules, input } = val;
                  return (
                    <FormItem label={label} key={field}>
                      {getFieldDecorator(field, {
                        initialValue: input.initialValue,
                        rules,
                      })(
                        <Input
                          title={input.title}
                          disabled={input.disabled}
                          placeholder={input.placeholder}
                        />
                      )}
                    </FormItem>
                  );
                })}
                {showEdit ? (
                  <FormItem label="生效时间">
                    {getFieldDecorator("expire_in", {
                      initialValue: 1,
                    })(
                      <RadioGroup>
                        <Radio value={1}>1天</Radio>
                        <Radio value={3}>3天</Radio>
                        <Radio value={7}>7天</Radio>
                        <Radio value={30}>30天</Radio>
                      </RadioGroup>
                    )}
                  </FormItem>
                ) : (
                  <FormItem label="温馨提示">{`模板链接已替换，还剩${day}天${hours}小时失效`}</FormItem>
                )}
              </Form>
            </Col>
            <Col>
              <Row type="flex" justify="center">
                <Col>
                  {showEdit ? (
                    <Button type="primary" onClick={handleOk}>
                      确定
                    </Button>
                  ) : (
                    <Button type="primary" onClick={handleCancel}>
                      取消替换
                    </Button>
                  )}
                </Col>
              </Row>
            </Col>
          </Row>
        </Col>
        <Col span={10} pull={1}>
          {/* <Input.TextArea rows="10" /> */}
        </Col>
      </Row>
      <Row style={{ marginTop: 40 }}>
        <Col style={{ fontWeight: "bolder", fontSize: "16px" }}>
          注：1、现只适用于“快件取出通知模板”。2、用户点击模板后跳转到您指定的链接和小程序。3、跳转小程序需要公众号先关联后才可生效。
        </Col>
      </Row>
    </div>
  );
};

export default connect(({ massPush, platform }) => ({
  templateData: massPush.templateData,
  platformList: platform.platformList,
}))(Form.create()(ChangeTemplateLink));
